package com.power.sifa.approve.dao.impl;

import com.plf.core.common.dao.OffersetTransformers;
import com.power.sifa.approve.dao.Apl_arrive_personDaoCustom;
import com.power.sifa.approve.model.pageInfo.Apl_arrive_personPageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
* 送达详情送达人 持久层实现(hibernate)
*/

@Slf4j
@Repository
public class Apl_arrive_personDaoImpl implements Apl_arrive_personDaoCustom {

    private final EntityManager entityManager;

    public Apl_arrive_personDaoImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public List<Map<String, Object>> findArriveListByPhone(Apl_arrive_personPageInfo pageInfo) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

        StringBuffer sql = new StringBuffer("select A.*, B.applyid, B.acceptcode from apl_arrive_person A join apl_arrive_detail B ON A.recordid = B.id  where 1=1  ");

        List<Object> paramsList = new ArrayList<>();
        int index = 1;
        // 由申请流水号调整为案号查询
        if (StringUtils.isNotEmpty(pageInfo.getF_acceptcode())) {
            sql.append(" and B.acceptcode like ?" + index++);
            paramsList.add("%" + pageInfo.getF_acceptcode() + "%");
        }

        if (StringUtils.isNotEmpty(pageInfo.getF_phone())) {
            sql.append(" and A.phone like ?" + index++);
            paramsList.add("%" + pageInfo.getF_phone() + "%");
        }

        // 排序
        sql.append(" order by A.sendtime desc ");
        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
        log.info(sql.toString());

        // 添加条件
        for (int i = 0; i <= paramsList.size() - 1; i++) {
            query.setParameter(i + 1, paramsList.get(i));
        }
        // 查询总数
        pageInfo.setAllcount(query.getResultList().size());
        // 分页
        if (pageInfo.getAllcount() > 0) {
            int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
            result = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
        }
        return result;

    }
}